package thread;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author: feiwang_6
 * @create: 2020/6/9 15:29
 * @description:
 */
public class ForkJoinTest extends RecursiveTask<Integer> {
    private List<Integer> list;
    private int start;
    private int end;

    private ForkJoinTest(List<Integer> list, int start, int end) {
        this.list = list;
        this.end= end;
        this.start = start;
    }
    
    public ForkJoinTest(List<Integer> list) {
        this.list = list;
        this.start = 0;
        this.end = list.size() - 1;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        if(start + 1 >= end){
            return list.get(start) + list.get(end);
        } else {
            int middle = (start + end) / 2;
            ForkJoinTest leftTask = new ForkJoinTest(list, start, middle);
            ForkJoinTest rightTask = new ForkJoinTest(list, middle + 1, end);
            // 执行子任务
            leftTask.fork();
            rightTask.fork();
            // 等待子任务执行完，并得到其结果
            int leftResult=leftTask.join();
            int rightResult=rightTask.join();
            // 合并子任务
            sum = leftResult + rightResult;
        }
        return sum;
    }
    
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTest task = new ForkJoinTest(list);
        ForkJoinTask<Integer> submit = forkJoinPool.submit(task);
        try {
            System.out.println(submit.get());
        } catch (Exception e) {
            if(task.isCompletedAbnormally()){
                System.out.println("111111111111111111111111111");
            }
            e.printStackTrace();
        }
    }
}
